package com.e0box.game.logicGraphics.display
{
	import com.e0box.game.logicGraphics.Game;
	import com.e0box.game.logicGraphics.Options;
	
	import starling.display.Image;
	import starling.textures.Texture;
	
	import utils.ObjectArray;
	
	public class Tile extends Image
	{
		public static const STATE_BLANK:uint = 0;
		public static const STATE_FLAG:uint = 1;
		public static const STATE_BLOCK:uint = 2;
		
		private static var _freePool:Vector.<Tile> = new Vector.<Tile>();
		private static var _usePool:Vector.<Tile> = new Vector.<Tile>();
		private static var _colorDisc:ObjectArray = new ObjectArray();
		
		public var tileX:uint;
		public var tileY:uint;
		
		private var _state:uint;
		private var _color:uint;
		
		public function Tile()
		{
			super(Game.instance.assets.getTexture(Options.TILE_SKIN_BLANK));
			
			_state = STATE_BLANK;
			touchable = false;
		}
		
		public function setState(state:uint, color:uint = 0xffffff):void
		{
			switch(state)
			{
				case STATE_BLANK:
					texture = Game.instance.assets.getTexture(Options.TILE_SKIN_BLANK);
					break;
				
				case STATE_FLAG:
					texture = Game.instance.assets.getTexture(Options.TILE_SKIN_FLAG);
					break;
				
				case STATE_BLOCK:
					if(!_colorDisc.containsKey(color))
					{
						_colorDisc.put(color, Texture.fromColor(Options.TILE_SIZE, Options.TILE_SIZE, 0xff000000 | color));
					}
					texture = _colorDisc.getValueByKey(color) as Texture;
					_color = color;
					break;
				
				default:
					throw new Error("error state:" + state);
					break;
			}
			_state = state;
			
		}
		
		public function getState():uint
		{
			return _state;
		}
		
		public function output():uint
		{
			if(_state == STATE_BLOCK)
			{
				return _color;
			}
			
			return _state;
		}
		
		public function getColor():uint
		{
			return _color;
		}
		
		public function free():void
		{
			tileX = 0;
			tileY = 0;
			_state = STATE_BLANK;
			_color = 0;
			
			removeFromParent(false);
			
			_freePool.push(this);
			
			var index:int = _usePool.indexOf(this);
			
			if(index == -1)
			{
				throw new Error("remove tile which unuse in usePool.");
			}
			else
			{
				_usePool.splice(index, 1);
			}
		}
		
		public static function getTile():Tile
		{
			var tile:Tile;
			if(_freePool.length)
			{
				tile =  _freePool.pop();
			}
			else
			{
				tile =  new Tile();
			}
			
			_usePool.push(tile);
			
			return tile;
		}
		
		/**
		 * do not change pool out of this class
		 * @return 
		 * 
		 */		
		public static function getAllUseTiles():Vector.<Tile>
		{
			return _usePool;
		}
		
		public static function getColorDisc():ObjectArray
		{
			return _colorDisc;
		}
		
	}
}